import 'dart:io';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class SimpleVideoPlayer extends StatefulWidget {
  final File videoFile;

  const SimpleVideoPlayer({
    super.key,
    required this.videoFile,
  });

  @override
  State<SimpleVideoPlayer> createState() => _SimpleVideoPlayerState();
}

class _SimpleVideoPlayerState extends State<SimpleVideoPlayer> {
  VideoPlayerController? _controller;
  bool _isInitialized = false;
  bool _hasError = false;
  String _errorMessage = '';
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializePlayer();
  }

  Future<void> _initializePlayer() async {
    setState(() {
      _isLoading = true;
      _hasError = false;
      _isInitialized = false;
    });

    try {
      print('开始初始化视频: ${widget.videoFile.path}');
      
      // 检查文件是否存在
      if (!await widget.videoFile.exists()) {
        throw '视频文件不存在';
      }

      final fileSize = await widget.videoFile.length();
      if (fileSize == 0) {
        throw '视频文件为空';
      }

      print('视频文件大小: ${(fileSize / 1024 / 1024).toStringAsFixed(1)} MB');

      // 先等待一小段时间让UI稳定
      await Future.delayed(const Duration(milliseconds: 100));

      // 创建控制器
      print('创建VideoPlayerController...');
      _controller = VideoPlayerController.file(widget.videoFile);
      
      print('开始初始化...');
      // 使用更长的超时时间并添加错误处理
      await _controller!.initialize().timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw '视频初始化超时，可能是文件格式不支持或文件损坏';
        },
      );
      
      // 检查初始化是否成功
      if (!_controller!.value.isInitialized) {
        throw '视频控制器初始化失败';
      }
      
      print('视频初始化成功');
      print('时长: ${_controller!.value.duration}');
      print('分辨率: ${_controller!.value.size}');
      print('是否有错误: ${_controller!.value.hasError}');
      
      if (_controller!.value.hasError) {
        throw _controller!.value.errorDescription ?? '未知播放错误';
      }

      if (mounted) {
        setState(() {
          _isInitialized = true;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('视频初始化失败: $e');
      
      // 清理失败的控制器
      _controller?.dispose();
      _controller = null;
      
      if (mounted) {
        String friendlyMessage = '视频播放失败';
        final errorStr = e.toString().toLowerCase();
        
        if (errorStr.contains('timeout') || errorStr.contains('超时')) {
          friendlyMessage = '视频加载超时\n可能是文件过大或格式不支持';
        } else if (errorStr.contains('format') || errorStr.contains('codec')) {
          friendlyMessage = '不支持的视频格式\n请尝试MP4格式的视频';
        } else if (errorStr.contains('permission') || errorStr.contains('access')) {
          friendlyMessage = '文件访问权限问题\n请重新选择目录';
        }
        
        setState(() {
          _hasError = true;
          _errorMessage = friendlyMessage;
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      );
    }

    if (_hasError) {
      return Container(
        color: Colors.black,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.error_outline,
                color: Colors.white,
                size: 64,
              ),
              const SizedBox(height: 16),
              Text(
                '视频加载失败',
                style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                _errorMessage,
                style: const TextStyle(color: Colors.white70),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: _initializePlayer,
                icon: const Icon(Icons.refresh),
                label: const Text('重试'),
              ),
            ],
          ),
        ),
      );
    }

    if (!_isInitialized || _controller == null) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: Text(
            '视频未就绪',
            style: TextStyle(color: Colors.white),
          ),
        ),
      );
    }

    return Container(
      color: Colors.black,
      child: Center(
        child: AspectRatio(
          aspectRatio: _controller!.value.aspectRatio,
          child: Stack(
            children: [
              VideoPlayer(_controller!),
              _buildControls(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildControls() {
    return GestureDetector(
      onTap: () {
        if (_controller!.value.isPlaying) {
          _controller!.pause();
        } else {
          _controller!.play();
        }
        setState(() {});
      },
      child: Container(
        color: Colors.transparent,
        child: Center(
          child: AnimatedOpacity(
            opacity: _controller!.value.isPlaying ? 0.0 : 1.0,
            duration: const Duration(milliseconds: 300),
            child: Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: Colors.black54,
                shape: BoxShape.circle,
              ),
              child: Icon(
                _controller!.value.isPlaying ? Icons.pause : Icons.play_arrow,
                size: 40,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}